import React, { useState, useEffect, useRef } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import io from 'socket.io-client';
import styles from './Chat.module.css';
import  {http,host,port} from '../utils/host'
const Chat = () => {
    const { conversationId, receiverId } = useParams();
    const navigate = useNavigate();
    const [messages, setMessages] = useState([]);
    const [newMessage, setNewMessage] = useState('');
    const [socket, setSocket] = useState(null);
    const [isTyping, setIsTyping] = useState(false);
    const [receiverInfo, setReceiverInfo] = useState(null);
    const [currentConversationId, setCurrentConversationId] = useState(conversationId);
    const [showEmojiPicker, setShowEmojiPicker] = useState(false);
    const [showAttachmentPanel, setShowAttachmentPanel] = useState(false);
    const messagesEndRef = useRef(null);
    const fileInputRef = useRef(null);
    const imageInputRef = useRef(null);
    
    // 表情数据
    const emojis = [
        '😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇',
        '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚',
        '😋', '😛', '😝', '😜', '🤪', '🤨', '🧐', '🤓', '😎', '🤩',
        '🥳', '😏', '😒', '😞', '😔', '😟', '😕', '🙁', '☹️', '😣',
        '😖', '😫', '😩', '🥺', '😢', '😭', '😤', '😠', '😡', '🤬',
        '🤯', '😳', '🥵', '🥶', '😱', '😨', '😰', '😥', '😓', '🤗',
        '🤔', '🤭', '🤫', '🤥', '😶', '😐', '😑', '😯', '😦', '😧',
        '😮', '😲', '🥱', '😴', '🤤', '😪', '😵', '🤐', '🥴', '🤢',
        '🤮', '🤧', '😷', '🤒', '🤕', '🤑', '🤠', '💩', '👻', '💀',
        '☠️', '👽', '👾', '🤖', '😺', '😸', '😹', '😻', '😼', '😽',
        '🙀', '😿', '😾', '🙈', '🙉', '🙊', '💌', '💘', '💝', '💖',
        '💗', '💓', '💞', '💕', '💟', '❣️', '💔', '❤️', '🧡', '💛',
        '💚', '💙', '💜', '🖤', '💯', '💢', '💥', '💫', '💦', '💨',
        '🕳️', '💬', '🗨️', '🗯️', '💭', '💤', '👋', '🤚', '🖐️', '✋',
        '🖖', '👌', '🤌', '🤏', '✌️', '🤞', '🤟', '🤘', '🤙', '👈',
        '👉', '👆', '🖕', '👇', '☝️', '👍', '👎', '✊', '👊', '🤛',
        '🤜', '👏', '🙌', '👐', '🤲', '🤝', '🙏', '✍️', '💪', '🦾',
        '🦿', '🦵', '🦶', '👂', '🦻', '👃', '🧠', '🫀', '🫁', '🦷',
        '🦴', '👀', '👁️', '👅', '👄', '💋', '🩸', '🦠', '💉', '💊'
    ];
    
    // 获取实际的接收者ID
    const actualReceiverId = receiverId || conversationId;
    
    // 获取当前用户信息
    const getUserInfo = () => {
        const userInfo = localStorage.getItem('userInfo');
        if (userInfo) {
            const parsed = JSON.parse(userInfo);
            return {
                _id: parsed.userId,
                username: parsed.username
            };
        }
        // 如果没有用户信息，使用默认值（仅用于测试）
        return {
            _id: '688cb2ff5e9bdf7c861dcd92',
            username: '张三'
        };
    };
    
    const currentUser = getUserInfo();

    useEffect(() => {
        // 连接WebSocket
        const newSocket = io(`${http}${host}${port}`, {
            transports: ['websocket', 'polling'],
            reconnection: true,
            reconnectionAttempts: 5,
            reconnectionDelay: 1000
        });
        setSocket(newSocket);

        // 用户登录到WebSocket
        newSocket.emit('user_login', {
            userId: currentUser._id,
            username: currentUser.username
        });

        // 连接成功
        newSocket.on('connect', () => {
            console.log('WebSocket连接成功');
        });

        // 连接错误
        newSocket.on('connect_error', (error) => {
            console.error('WebSocket连接错误:', error);
        });

        // 接收消息
        newSocket.on('receive_message', (message) => {
            console.log('收到新消息:', message);
            setMessages(prev => {
                // 检查消息是否已经存在，避免重复添加
                const messageExists = prev.some(msg => msg._id === message._id);
                if (!messageExists) {
                    // 按时间顺序插入新消息
                    const newMessages = [...prev, message].sort((a, b) => 
                        new Date(a.timestamp) - new Date(b.timestamp)
                    );
                    return newMessages;
                }
                return prev;
            });
        });

        // 消息发送确认
        newSocket.on('message_sent', (data) => {
            console.log('消息发送确认:', data);
            if (data.success && data.data) {
                // 检查消息是否已经存在，避免重复添加
                setMessages(prev => {
                    const messageExists = prev.some(msg => msg._id === data.data._id);
                    if (!messageExists) {
                        // 按时间顺序插入新消息
                        const newMessages = [...prev, data.data].sort((a, b) => 
                            new Date(a.timestamp) - new Date(b.timestamp)
                        );
                        return newMessages;
                    }
                    return prev;
                });
            }
        });

        // 监听用户正在输入
        newSocket.on('user_typing', (data) => {
            if (data.senderId === actualReceiverId) {
                setIsTyping(data.isTyping);
            }
        });

        return () => {
            newSocket.disconnect();
        };
    }, [currentUser._id, currentUser.username, actualReceiverId]);

    useEffect(() => {
        // 获取或创建会话
        fetchOrCreateConversation();
        // 获取接收者信息
        fetchReceiverInfo();
    }, [actualReceiverId]);

    useEffect(() => {
        // 滚动到底部
        scrollToBottom();
    }, [messages]);

    // 点击外部关闭表情选择器和附件面板
    useEffect(() => {
        const handleClickOutside = (event) => {
            if (showEmojiPicker && !event.target.closest(`.${styles.emojiPicker}`) && !event.target.closest(`.${styles.emojiButton}`)) {
                setShowEmojiPicker(false);
            }
            if (showAttachmentPanel && !event.target.closest(`.${styles.attachmentPanel}`) && !event.target.closest(`.${styles.attachmentButton}`)) {
                setShowAttachmentPanel(false);
            }
        };

        document.addEventListener('mousedown', handleClickOutside);
        return () => {
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, [showEmojiPicker, showAttachmentPanel]);

    const fetchOrCreateConversation = async () => {
        try {
            console.log('开始创建会话...');
            console.log('参与者1:', currentUser._id);
            console.log('参与者2:', actualReceiverId);
            
            // 创建或获取会话
            const response = await fetch(`${http}${host}${port}/api/messages/conversation`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    participant1Id: currentUser._id,
                    participant2Id: actualReceiverId
                })
            });

            const data = await response.json();
            console.log('会话创建响应:', data);
            
            if (data.code === 200) {
                setCurrentConversationId(data.data._id);
                console.log('会话创建成功，ID:', data.data._id);
                // 获取聊天记录
                fetchChatHistory(data.data._id);
            } else {
                console.error('创建会话失败:', data.message);
            }
        } catch (error) {
            console.error('创建会话错误:', error);
        }
    };

    const fetchChatHistory = async (conversationId) => {
        try {
            console.log('获取聊天记录，会话ID:', conversationId);
            const response = await fetch(`${http}${host}${port}/api/messages/${conversationId}`);
            const data = await response.json();
            
            console.log('聊天记录响应:', data);
            
            if (data.code === 200) {
                // 确保消息按时间顺序排列
                const sortedMessages = (data.data.messages || []).sort((a, b) => 
                    new Date(a.timestamp) - new Date(b.timestamp)
                );
                setMessages(sortedMessages);
            } else {
                console.error('获取聊天记录失败:', data.message);
            }
        } catch (error) {
            console.error('获取聊天记录失败:', error);
        }
    };

    const fetchReceiverInfo = async () => {
        try {
            console.log('获取接收者信息，ID:', actualReceiverId);
            const response = await fetch(`${http}${host}${port}/userById/${actualReceiverId}`);
            const data = await response.json();
            
            console.log('接收者信息响应:', data);
            
            if (data.code === 200) {
                setReceiverInfo(data.data);
            } else {
                console.error('获取用户信息失败:', data.msg);
            }
        } catch (error) {
            console.error('获取用户信息失败:', error);
        }
    };

    const scrollToBottom = () => {
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    };

    const handleSendMessage = async () => {
        if (!newMessage.trim() || !socket) return;

        const messageData = {
            senderId: currentUser._id,
            receiverId: actualReceiverId,
            content: newMessage.trim(),
            messageType: 'text'
        };

        console.log('发送消息:', messageData);

        // 发送WebSocket消息（WebSocket会负责保存到数据库）
        socket.emit('send_message', messageData);

        // 清空输入框
        setNewMessage('');
        
        // 添加发送状态提示
        console.log('消息已发送，等待确认...');
    };

    const handleKeyPress = (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            handleSendMessage();
        }
    };

    const handleTyping = (e) => {
        setNewMessage(e.target.value);
        
        // 发送正在输入状态
        if (socket) {
            socket.emit('typing', {
                receiverId: actualReceiverId,
                isTyping: e.target.value.length > 0
            });
        }
    };

    // 切换表情选择器显示状态
    const toggleEmojiPicker = () => {
        setShowEmojiPicker(!showEmojiPicker);
    };

    // 选择表情
    const selectEmoji = (emoji) => {
        setNewMessage(prev => prev + emoji);
        setShowEmojiPicker(false);
        
        // 聚焦到输入框
        const textarea = document.querySelector(`.${styles.messageInput}`);
        if (textarea) {
            textarea.focus();
        }
    };

    // 切换附件面板显示状态
    const toggleAttachmentPanel = () => {
        setShowAttachmentPanel(!showAttachmentPanel);
        setShowEmojiPicker(false); // 关闭表情选择器
    };

    // 处理图片选择
    const handleImageSelect = () => {
        imageInputRef.current?.click();
    };

    // 处理文件选择
    const handleFileSelect = () => {
        fileInputRef.current?.click();
    };

    // 处理图片上传
    const handleImageUpload = (event) => {
        const file = event.target.files[0];
        if (file) {
            if (file.type.startsWith('image/')) {
                // 创建图片消息
                const reader = new FileReader();
                reader.onload = (e) => {
                    const imageData = e.target.result;
                    sendImageMessage(imageData, file.name);
                };
                reader.readAsDataURL(file);
            } else {
                alert('请选择图片文件');
            }
        }
        // 清空input值，允许重复选择同一文件
        event.target.value = '';
    };

    // 处理文件上传
    const handleFileUpload = (event) => {
        const file = event.target.files[0];
        if (file) {
            // 创建文件消息
            const reader = new FileReader();
            reader.onload = (e) => {
                const fileData = e.target.result;
                sendFileMessage(fileData, file.name, file.size);
            };
            reader.readAsDataURL(file);
        }
        // 清空input值，允许重复选择同一文件
        event.target.value = '';
    };

    // 发送图片消息
    const sendImageMessage = (imageData, fileName) => {
        if (!socket) return;

        const messageData = {
            senderId: currentUser._id,
            receiverId: actualReceiverId,
            content: imageData,
            messageType: 'image',
            fileName: fileName
        };

        console.log('发送图片消息:', messageData);
        socket.emit('send_message', messageData);
        setShowAttachmentPanel(false);
    };

    // 发送文件消息
    const sendFileMessage = (fileData, fileName, fileSize) => {
        if (!socket) return;

        const messageData = {
            senderId: currentUser._id,
            receiverId: actualReceiverId,
            content: fileData,
            messageType: 'file',
            fileName: fileName,
            fileSize: fileSize
        };

        console.log('发送文件消息:', messageData);
        socket.emit('send_message', messageData);
        setShowAttachmentPanel(false);
    };

    const formatTime = (timestamp) => {
        if (!timestamp) return '';
        const date = new Date(timestamp);
        return date.toLocaleTimeString('zh-CN', { 
            hour: '2-digit', 
            minute: '2-digit' 
        });
    };

    return (
        <div className={styles.chatContainer}>
            {/* 聊天头部 */}
            <div className={styles.chatHeader}>
                <button 
                    className={styles.backButton}
                    onClick={() => navigate('/layout/xiaoxi')}
                >
                    ← 返回
                </button>
                <div className={styles.userInfo}>
                    <div className={styles.avatar}>
                        {receiverInfo?.avatarImage ? (
                            <img src={receiverInfo.avatarImage} alt="头像" />
                        ) : (
                            <div className={styles.defaultAvatar}>
                                {receiverInfo?.username?.charAt(0) || 'U'}
                            </div>
                        )}
                    </div>
                    <div className={styles.userDetails}>
                        <div className={styles.username}>
                            {receiverInfo?.username || '用户'}
                        </div>
                        <div className={styles.status}>
                            {isTyping ? '正在输入...' : '在线'}
                        </div>
                    </div>
                </div>
            </div>

            {/* 消息列表 */}
            <div className={styles.messagesContainer}>
                {messages.map((message, index) => {
                    // 判断消息是否由当前用户发送
                    // 后端返回的senderId是populated的对象
                    let isSentByMe = false;
                    let senderName = '用户';
                    
                    if (message.senderId && typeof message.senderId === 'object') {
                        // senderId是populated的对象
                        isSentByMe = message.senderId._id === currentUser._id;
                        senderName = message.senderId.username || '用户';
                    } else if (typeof message.senderId === 'string') {
                        // senderId是字符串（ObjectId）
                        isSentByMe = message.senderId === currentUser._id;
                        senderName = isSentByMe ? currentUser.username : (receiverInfo?.username || '用户');
                    }
                    
                    console.log('消息显示逻辑:', {
                        messageId: message._id,
                        senderId: message.senderId,
                        senderIdType: typeof message.senderId,
                        currentUserId: currentUser._id,
                        isSentByMe,
                        senderName,
                        messageContent: message.content
                    });
                    
                    return (
                        <div 
                            key={message._id || index} 
                            className={`${styles.messageItem} ${
                                isSentByMe ? styles.sentMessage : styles.receivedMessage
                            }`}
                        >
                            <div className={styles.messageContent}>
                                {!isSentByMe && (
                                    <div className={styles.senderName}>
                                        {senderName || '未知用户'}
                                    </div>
                                )}
                                <div className={styles.messageText}>
                                    {message.messageType === 'image' ? (
                                        <div className={styles.imageMessage}>
                                            <img 
                                                src={message.content} 
                                                alt={message.fileName || '图片'} 
                                                className={styles.messageImage}
                                                onClick={() => window.open(message.content, '_blank')}
                                            />
                                            {message.fileName && (
                                                <div className={styles.fileName}>{message.fileName}</div>
                                            )}
                                        </div>
                                    ) : message.messageType === 'file' ? (
                                        <div className={styles.fileMessage}>
                                            <div className={styles.fileIcon}>📎</div>
                                            <div className={styles.fileInfo}>
                                                <div className={styles.fileName}>{message.fileName}</div>
                                                <div className={styles.fileSize}>
                                                    {(message.fileSize / 1024 / 1024).toFixed(2)} MB
                                                </div>
                                            </div>
                                            <button 
                                                className={styles.downloadButton}
                                                onClick={() => {
                                                    const link = document.createElement('a');
                                                    link.href = message.content;
                                                    link.download = message.fileName;
                                                    link.click();
                                                }}
                                            >
                                                下载
                                            </button>
                                        </div>
                                    ) : (
                                        message.content || '消息内容为空'
                                    )}
                                </div>
                                <div className={styles.messageTime}>
                                    {formatTime(message.timestamp)}
                                </div>
                                {isSentByMe && (
                                    <div className={styles.messageStatus}>
                                        {message.isRead ? '✓✓' : '✓'}
                                    </div>
                                )}
                            </div>
                        </div>
                    );
                })}
                <div ref={messagesEndRef} />
            </div>

            {/* 输入区域 */}
            <div className={styles.inputContainer}>
                {!showAttachmentPanel && (
                    <div className={styles.inputWrapper}>
                        <textarea
                            value={newMessage}
                            onChange={handleTyping}
                            onKeyPress={handleKeyPress}
                            placeholder="输入消息..."
                            className={styles.messageInput}
                            rows="1"
                        />
                        
                        {/* 表情按钮 */}
                        <button 
                            type="button"
                            className={styles.emojiButton}
                            onClick={toggleEmojiPicker}
                            title="表情"
                        >
                            😊
                        </button>
                        
                        {/* 表情选择器 */}
                        {showEmojiPicker && (
                            <div className={styles.emojiPicker}>
                                <div className={styles.emojiGrid}>
                                    {emojis.map((emoji, index) => (
                                        <button
                                            key={index}
                                            className={styles.emojiItem}
                                            onClick={() => selectEmoji(emoji)}
                                            title={emoji}
                                        >
                                            {emoji}
                                        </button>
                                    ))}
                                </div>
                            </div>
                        )}
                        
                        <button 
                            onClick={handleSendMessage}
                            className={styles.sendButton}
                            disabled={!newMessage.trim()}
                        >
                            发送
                        </button>
                        
                        {/* 附件按钮 */}
                        <button 
                            type="button"
                            className={styles.attachmentButton}
                            onClick={toggleAttachmentPanel}
                            title="附件"
                        >
                            +
                        </button>
                    </div>
                )}
                
                {/* 附件面板 */}
                {showAttachmentPanel && (
                    <div className={styles.attachmentPanel}>
                        <div className={styles.attachmentHeader}>
                            <span>选择附件</span>
                            <button 
                                className={styles.closeButton}
                                onClick={() => setShowAttachmentPanel(false)}
                            >
                                ✕
                            </button>
                        </div>
                        <div className={styles.attachmentOptions}>
                            <div className={styles.attachmentOption} onClick={handleImageSelect}>
                                <div className={styles.attachmentIcon}>🖼️</div>
                                <div className={styles.attachmentLabel}>图片</div>
                            </div>
                            <div className={styles.attachmentOption} onClick={handleFileSelect}>
                                <div className={styles.attachmentIcon}>📎</div>
                                <div className={styles.attachmentLabel}>文件</div>
                            </div>
                        </div>
                    </div>
                )}
                
                {/* 隐藏的文件输入 */}
                <input
                    ref={imageInputRef}
                    type="file"
                    accept="image/*"
                    onChange={handleImageUpload}
                    style={{ display: 'none' }}
                />
                <input
                    ref={fileInputRef}
                    type="file"
                    accept=".doc,.docx,.pdf,.txt,.xls,.xlsx,.ppt,.pptx"
                    onChange={handleFileUpload}
                    style={{ display: 'none' }}
                />
            </div>
        </div>
    );
};

export default Chat; 